package com.sds.book.sentinel.dynamic.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.websocket.server.PathParam;
import java.util.Collections;

@RestController
public class ParamRuleController {

    private String resourceName = "com.sds.book.sentinel.dynamic.controller.ParamRuleController:sayHello(java.lang.String)";

    @PostConstruct
    public void initParamRule() {
        ParamFlowRule rule = new ParamFlowRule(resourceName);
        rule.setParamIdx(0);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(1);
        ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
    }

    @SentinelResource
    @GetMapping("/hello")
    public String sayHello(@PathParam("id") String id) {
        return "access success";
    }

}
